<template>
    <div id="cesium-container" ref="cesiumContainer"></div>
</template>

<script setup>
import { onMounted, ref, markRaw, onUnmounted, defineExpose } from 'vue';
import * as Cesium from 'cesium';
import imageUrl from '@/assets/home/bg.png'
import icon1 from '@/assets/home/icon1.png'
import icon2 from '@/assets/home/icon2.png'
import icon3 from '@/assets/home/icon3.png'
import icon4 from '@/assets/home/icon4.png'
const emit = defineEmits(['mapClick'])
// 显示控制变量
const showImage = ref(true);
const showPoints = ref(true);

// 存储实体引用
const imageEntity = ref(null);
const pointEntities = ref([]);

const dangerLocationData = [
    {
        lon: 114.60255755918668, lat: 30.45396036786957, icon: icon1, text: "新烽园区滴灌设备",
        textColor: Cesium.Color.WHITE, textSize: 16,
    },
    {
        lon: 114.60181735120385, lat: 30.454187442372657, icon: icon3, text: "新烽园区北侧监测站点",
        textColor: Cesium.Color.WHITE, textSize: 16,
    },
    {
        lon: 114.60256775271668, lat: 30.45326252888005, icon: icon3, text: "新烽园区南侧监测站点",
        textColor: Cesium.Color.WHITE, textSize: 16,
    },
    {
        lon: 114.59967078559204, lat: 30.452032732989146, icon: icon2, text: "韶华路旁湖泊",
        textColor: Cesium.Color.WHITE, textSize: 16,
    },
    {
        lon: 114.60382081505499, lat: 30.453080767487208, icon: icon4, text: "玉屏南路旁引水工",
        textColor: Cesium.Color.WHITE, textSize: 16,
    },
]

const cesiumContainer = ref(null);
let viewer = null;
let handler = null;
const startLon = 114.59990004313785;
const startLat = 30.45372409223496;

const imagePointData = { lon: 114.59990004313785, lat: 30.45372409223496 }
const cameraHeight = 1000;

const imageCenterLon = imagePointData.lon;
const imageCenterLat = imagePointData.lat;
const imageWidth = 9 / (cameraHeight * 1.5);
const imageHeight = 16 / (cameraHeight * 1.5);
const imageRotationAngle = 90 * Math.PI / 180;
const imageOpacity = 1;
let imageAspectRatio = 1

// 切换图片显示状态
const toggleImageVisibility = (visible) => {
    showImage.value = visible;
    if (imageEntity.value) {
        imageEntity.value.show = showImage.value;
    }
};

// 切换点位显示状态
const togglePointsVisibility = (visible) => {
    showPoints.value = visible;
    pointEntities.value.forEach(entity => {
        entity.show = showPoints.value;
    });
};

onMounted(() => {
    try {
        viewer = markRaw(new Cesium.Viewer(cesiumContainer.value, {
            terrainProvider: new Cesium.EllipsoidTerrainProvider(),
            baseLayerPicker: false,
            timeline: false,
            animation: false,
            geocoder: false,
            infoBox: false,
            selectionIndicator: false,
            skyBox: false,
            scene3DOnly: false,
            homeButton: false,
            navigationHelpButton: false,
            sceneModePicker: false,
            contextOptions: {
                webgl: {
                    preserveDrawingBuffer: false,
                    failIfMajorPerformanceCaveat: false
                }
            },
            sceneMode: Cesium.SceneMode.SCENE2D,
        }))

        viewer.imageryLayers.addImageryProvider(
            new Cesium.UrlTemplateImageryProvider({
                url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
                subdomains: ['1', '2', '3', '4'],
                layer: 'tdtImgLayer',
                style: 'default',
                format: 'image/png',
                tileMatrixSetID: 'GoogleMapsCompatible',
                tileSize: 512,
                maximumLevel: 19,
                enablePickFeatures: false,
                credit: '',
                show: true
            })
        )

        viewer.scene.globe.maximumScreenSpaceError = 0.5;
        viewer.scene.fxaa = true;
        viewer.scene.postProcessStages.fxaa.enabled = true;

        loadImageAndGetAspect(imageUrl).then(aspect => {
            imageAspectRatio = aspect;
            createBackgroundImage();
            setView();
            initMouseInteraction();
            createPoint(dangerLocationData);
        }).catch(error => {
            console.error("图片加载失败:", error);
            imageAspectRatio = 1;
            createBackgroundImage();
            setView();
            initMouseInteraction();
            createPoint(dangerLocationData);
        });
    } catch (error) {
        console.error("Cesium初始化错误:", error);
    }
});

function loadImageAndGetAspect(url) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => {
            resolve(img.width / img.height);
        };
        img.onerror = reject;
        img.src = url;
    });
}

const createPoint = (data) => {
    if (!data?.length) return
    data.map(item => {
        const entity = new Cesium.Entity({
            position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat),
            billboard: {
                image: item.icon,
                width: 64,
                height: 64,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e3, 0.4),
                show: showPoints.value // 绑定显示状态
            },
            label: {
                text: item.text,
                font: `bold ${item.textSize || 14}px sans-serif`,
                fillColor: Cesium.Color.WHITE,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -50),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                showBackground: true,
                backgroundColor: Cesium.Color.fromBytes(36, 136, 110),
                backgroundPadding: new Cesium.Cartesian2(8, 4),
                show: showPoints.value // 绑定显示状态
            },
            properties: {
                isCustomIcon: true,
                iconType: item.icon === icon1 ? 'icon1' :
                    item.icon === icon2 ? 'icon2' : 'icon3',
                originalData: item
            },
            show: showPoints.value // 整体实体显示状态
        });

        viewer.entities.add(entity);
        pointEntities.value.push(entity); // 存储实体引用
    })
}

const setView = () => {
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(startLon, startLat, cameraHeight),
        orientation: {
            heading: Cesium.Math.toRadians(90),
            roll: 0
        },
    });
};
const clickData = ref({
    customIconFlag: false,
    longitude: null,
    latitude: null,
})
const initMouseInteraction = () => {
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction((click) => {
        const pickedObject = viewer.scene.pick(click.position);
        if (pickedObject && pickedObject.id && pickedObject.id.properties) {
            try {
                const isCustomIcon = pickedObject.id.properties.isCustomIcon;
                if (isCustomIcon && isCustomIcon.getValue) {
                    const customIconFlag = isCustomIcon.getValue(Cesium.JulianDate.now());
                    if (customIconFlag) {
                        const position = pickedObject.id.position.getValue(Cesium.JulianDate.now());
                        const cartographic = Cesium.Cartographic.fromCartesian(position);
                        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
                        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
                        const iconType = pickedObject.id.properties.iconType.getValue(Cesium.JulianDate.now());
                        const originalData = pickedObject.id.properties.originalData.getValue(Cesium.JulianDate.now());
                        console.log('点击了自定义图标:', { iconType, longitude, latitude, originalData });
                        clickData.value = {
                            customIconFlag: true,
                            longitude: longitude,
                            latitude: latitude,
                        }
                        mapClick(clickData.value)
                        return;
                    }
                }
            } catch (error) {
                console.error('处理自定义图标点击时出错:', error);
            }
        }
        const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
        if (cartesian) {
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            const longitude = Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = Cesium.Math.toDegrees(cartographic.latitude);
            // console.log('点击位置坐标:', longitude, latitude);
            clickData.value = {
                customIconFlag: false,
                longitude: longitude,
                latitude: latitude,
            }
            mapClick(clickData.value)
        } else {
            console.log('未点击到有效位置');
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

const createBackgroundImage = () => {
    const corners = calculateImageCorners(
        imageCenterLon,
        imageCenterLat,
        imageWidth,
        imageHeight,
        imageRotationAngle
    );

    // 创建图片实体并存储引用
    imageEntity.value = viewer.entities.add({
        polygon: {
            hierarchy: new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(corners.flat())
            ),
            material: new Cesium.ImageMaterialProperty({
                image: imageUrl,
                transparent: true,
                alpha: imageOpacity
            }),
            classificationType: Cesium.ClassificationType.TERRAIN,
            allowPicking: false,
            perPositionHeight: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            zIndex: 0
        },
        show: showImage.value // 绑定显示状态
    });
};

function calculateImageCorners(centerLon, centerLat, imgWidth, imgHeight, imgRotation) {
    const halfWidth = imgWidth / 2;
    const halfHeight = imgHeight / 2;

    const relativePoints = [
        [-halfWidth, -halfHeight],
        [halfWidth, -halfHeight],
        [halfWidth, halfHeight],
        [-halfWidth, halfHeight]
    ];

    const cosAngle = Math.cos(imgRotation);
    const sinAngle = Math.sin(imgRotation);

    return relativePoints.map(point => {
        const [x, y] = point;
        const rotatedX = x * cosAngle - y * sinAngle;
        const rotatedY = x * sinAngle + y * cosAngle;
        const lon = centerLon + rotatedX;
        const lat = centerLat + rotatedY;
        return [lon, lat];
    });
}
const mapClick = (value) => {
    emit('mapClick', value)
}
// 暴露控制方法给父组件
defineExpose({
    toggleImageVisibility,
    togglePointsVisibility,
});

onUnmounted(() => {
    handler && handler.destroy();
    viewer && viewer.destroy();
});
</script>

<style scoped>
#cesium-container {
    /* width: 100%;
    height: 100vh;
    background-color: #000;
    position: absolute;
    top: 0;
    left: 0; */

}
</style>
<style>
.cesium-viewer-bottom {
    display: none;
}
</style>